package marco.android.CouchControl;

import java.io.IOException;
import java.util.UUID;
import marco.android.CouchControl.R;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothSocket;

public class BluetoothClient extends Connection
{
	private BluetoothAdapter mBluetoothAdapter = null;
	private static final String TAG = "BlueToothClient";
	
	public BluetoothClient()
	{		
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		mConnectionThread = new ConnectionThread("07293db4-a323-4e07-8b8b-250b340e42a4");
	}
	
	public void Initialize(String address, Integer port)
	{
		mServerAddress = address;
	}
	
	public void Start()
	{
		// If the bluetooth interface is not running, then
		// start a dialog to request that the user start it.
		if(mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled())
		{
			mListener.StartBluetoothActivityForResult();
		}
		mConnectionThread.start();
	}
	
	public void Stop()
	{
		if(mConnectionThread != null && mConnectionThread.isAlive())
		{
			mConnectionThread.interrupt();
		}
//		//Close the bluetooth thread.
//		synchronized(sLock)
//		{
//			mStop = true;
//			sLock.notify();
//			try
//			{
//				while(!mStopped)
//				{
//					sLock.wait(500);
//				}
//			}
//			catch(InterruptedException e)
//			{
//				e(e);
//			}
//		}
	}
	
//	private void Restart()
//	{
//		synchronized(sLock)
//		{
//			mStop = true;
//			sLock.notify();
//			try
//			{
//				while(!mStopped)
//				{
//					sLock.wait(500);
//				}
//			}
//			catch(InterruptedException e)
//			{
//				e(e);
//			}
//		}
//		mStop = false;
//		mStopped = false;
//		// new Thread(mBTLoop).start();
//	}
	
	public class ConnectionThread extends Thread
	{
		private UUID mUUID = null; // UUID.fromString("B16E28E1-0B68-28D8-5144-4D8E900D5ED2");
		BluetoothSocket mSocket = null;
		
		public ConnectionThread(String serviceUUID)
		{
			mUUID = UUID.fromString(serviceUUID);
		}
		
		private int Connect()
		{
			try
			{
				mSocket = mBluetoothAdapter.getRemoteDevice(mServerAddress).createRfcommSocketToServiceRecord(mUUID);
			}
			catch(IOException e)
			{
				Logs.e(TAG, e);
				return -1;
			}

			Logs.d(TAG, "socket created");
			try
			{
				mSocket.connect();
			}
			catch(IOException e)
			{
				Logs.e(TAG, e);
				return -1;
			}
			Logs.d(TAG, "connected");
			
			return(0);
		}
		
		private int SendEvent(Event e)
		{
			mByteStream.reset();
		    mNetIO.EventToByteArray(e);

		    try
		    {
			   mSocket.getOutputStream().write(mByteStream.toByteArray(), 0, mByteStream.size());
			   mSocket.getOutputStream().flush();
		    }
		    catch(IOException ex)
		    {
		    	return(-1);
		    }
			return(mByteStream.size());
		}
		
		@Override
		public void run()
		{
			while(!interrupted())
			{
				// Attempt to connect to the remote service.
				// BluetoothClient("B16E28E1-0B68-28D8-5144-4D8E900D5ED2");
				//BluetoothClient bc = new BluetoothClient("07293db4-a323-4e07-8b8b-250b340e42a4");
				//if(bc.Initialize(mBluetoothAdapter) < 0)
				if(Connect() < 0)
				{
					try
					{
						Thread.sleep(1000);
					}
					catch(InterruptedException e)
					{
						Logs.e(TAG, e);
						return;
					}
					continue;
				}

				Logs.d(TAG, "initialized");

				while(!interrupted())
				{
					synchronized(sLock)
					{
						try
						{
							sLock.wait();// wait for a new event
							{
								// woke up for data phase
								//if(bc.SendEvent(mEvent) < 0)
								if(SendEvent(mEvent) < 0)
								{
									// data phase crash,
									// reconnect
									break;
								}
							}
						}
						catch(InterruptedException e)
						{
							Logs.e(TAG, e);
						}
					}
				}
				try
				{
					Thread.sleep(2000);
				}
				catch(InterruptedException e)
				{
					Logs.e(TAG, e);
				}
			}
			
			mEvent.Source = 'E';
			SendEvent(mEvent);
		}
	}
	
	public Connection.IOMode GetMode()
	{
		return(Connection.IOMode.eBluetooth);
	}
}
